﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace nhCommon
{
    public sealed class NhSystem
    {
        /// <summary>
        /// 设置程序开机启动
        /// </summary>
        /// <param name="bIsAutoRun">自动运行状态</param>
        public static void SetAutoRun(bool bIsAutoRun)
        {
            string strAppPath = System.Windows.Forms.Application.ExecutablePath;
            string strAppName = System.IO.Path.GetFileName(strAppPath); //获取文件名
            try
            {
                RegistryKey reg = Registry.CurrentUser;
                RegistryKey run = reg.CreateSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\");

                if (bIsAutoRun)
                {
                    run.SetValue(strAppName, strAppPath);
                }
                else
                {
                    if (null != run.GetValue(strAppName))
                    {
                        run.DeleteValue(strAppName);
                    }
                }

                run.Close();
                reg.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        /// <summary>
        /// 判断是否开机启动
        /// </summary>
        /// <returns></returns>
        public static bool IsAutoRun()
        {
            string strAppPath = System.Windows.Forms.Application.ExecutablePath;
            string strAppName = System.IO.Path.GetFileName(strAppPath); //获取文件名
            try
            {
                RegistryKey reg = Registry.CurrentUser;
                RegistryKey software = reg.OpenSubKey(@"SOFTWARE");
                RegistryKey run = reg.OpenSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\");
                object key = run.GetValue(strAppName);
                software.Close();
                run.Close();
                if (null == key || !strAppPath.Equals(key.ToString()))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
    }
}
